#! /usr/bin/env python
#
# PyWS - Python WebServer 0.1
# This software is relased under GNU/GPL
#
# Copyleft 2009 Galatolo Federico
#
#
import socket, thread, random, commands, os
from confpars import *
from recv_parser import *
from pywscorelib import *
parser = confpars()
parser.open("pyws.cfg")
conf = parser.parse()

def server(client,address):
	while True:
		recv = client.recv(conf["recv_buff"])
		try:
			(page,get_args,post_args,cookies) = recv_parser(recv)
		except:
			client.send(conf["sintax_err"])
			client.close()
			return 0
		if len(page) > 0:
			try:
				reader = open(conf["www_path"]+page,"rb")
			except:
				client.send(conf["404_err"])
				client.close()
				return 0
		else:
			page = defindex(conf["www_path"])
		if page.find(".py") == -1:
			while True:
				read = reader.readline(conf["reader_buff"])
				if not read:
					break
				client.send(read)
			client.close()
			return 0
		else:
			output = commands.getoutput("python "+conf["www_path"]+page+" '"+unquote(str(get_args))+"' "+" '"+unquote(str(post_args))+"' "+" '"+unquote(str(cookies))+"' ")	
			client.send(output)
			client.close()
			return 0
	
print "Starting..."
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((conf["localhost"],conf["port"]))
sock.listen(conf["maxlisten"])
print "PyWS Up"

while True:
	(client,address) = sock.accept()
	thread.start_new_thread(server, (client,address))
sock.close()
